<?php
//app登录
namespace App\Http\Controllers\App;
use App\Http\Controllers\Controller;
use App\Models\AppActive;
use App\Models\Version;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Hash;
use Illuminate\Http\Request;
use App\Models\ShopClerk;
use App\Models\UserCheck;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;

class VersionController extends Controller
{
    /**
     * 客户端初始化接口
     * 1、检测APP是否需要升级
     */
    public function init(Request $request) {
        $rules = [
            'type'=>'required|in:android,ios',
            'version'=>'required',
            'device_id'=>'required|string'
        ];
        $messages = [
            'type.*'=>'手机是安卓还是苹果',
            'version.*'=>'请提交版本号',
            'device_id.*'=>'请提交设备号'
        ];
        $validator = Validator::make($request->all(), $rules,$messages);
        if ($validator->fails()) {
            return show(2003,$validator->errors()->first());
        }
        $appType = $request->type;
        $now_versions = $request->version;
        $version = Version::where(['status'=>1,'app_type'=>$appType])
            ->orderBy('id','desc')
            ->limit(1)
            ->first();
        if (!$version){
            //@todo
            Log::info('版本错误');
        }
        if($version->version > $now_versions) {
            $version->is_update = $version->is_force == 1 ? 2 : 1;
        }else {
            $version->is_update = 0;  // 0 不更新 ， 1需要更新, 2强制更新
        }
//        // 记录用户的基本信息 用于统计
        $actives = [
            'version' => $now_versions,
            'app_type' => $appType,
            'did' => $request->device_id,
            'version_code'=>1,
        ];
        try {
            AppActive::create($actives);
        }catch (\Exception $e) {
            return show(200, 'OK', $version);
        }

        return show(200, 'OK', $version);
    }
}
